/**
 * 
 * jquery提交多文件和普通参数
 * 
 * @author <b>欧建东2012-10-19改<br/>修正2.0版本IE6.0、搜狗提交到新窗口问题^_^<br/>
 *         Email:oyjd@163.com</b>
 * @version 2.0
 */
(function($) {
	var noop = function(){ return true; };
	var frameCount = 0;
	
	//设置默认参数
	$.uploadDefault = {
		url: '',
		fileIds: {},
		params: {},
		dataType: 'json',		
		onSend: noop,
		onComplate: noop
	};
	
	//函数构建
	$.upload = function(options) {	
		var opts = $.extend(jQuery.uploadDefault, options);
		if (opts.url == '') {
			return;
		}		
		var canSend = opts.onSend();
		if (!canSend) {
			return;
		}	
		
		var tmpName = 'upload_frame_' + (frameCount++);
		var iframe = $("<iframe style='display:none;' name='"+tmpName+"' id='"+tmpName+"'></iframe>");
		iframe.load(function() {
			var contents = $(this).contents().get(0);
			var data = $(contents).find('body').html();
			if(!data) return;
			if ('json' == opts.dataType) {
				data = eval('(' + data + ')');
			}
			opts.onComplate(data);
			setTimeout(function() {
				iframe.remove();
				form.remove();
			}, 2000);
		});
		iframe.appendTo("body");
		
		var form = $('<form method="post" style="display:none;" enctype="multipart/form-data" />').attr('name', 'form_' + tmpName);
		form.attr("target", tmpName).attr('action', opts.url);		
		var formHtml;
		//普通参数
		for (key in opts.params) {
			formHtml += '<input type="hidden" name="' + key + '" value="' + opts.params[key] + '">';
		}
		form.append(formHtml);
		//文件参数
		for (var i=0;i<opts.fileIds.length;i++) {
			var f=opts.fileIds[i];
			var oldElement = $("#"+f);
			var newElement = $(oldElement).clone();
			$(oldElement).attr('id', 'ajaxupload_'+f);
			$(oldElement).before(newElement);
			$(oldElement).appendTo(form);
		}		
		form.appendTo("body");	
		form.submit();
	};
	
	
	$.uploadDefaultEx = {
			url: '',
			formId: '',
			dataType: 'json',		
			onSend: noop,
			onComplate: noop
		};
	//函数构建
	$.uploadEx = function(options) {	
		var opts = $.extend(jQuery.uploadDefaultEx, options);
		if (opts.url == '') {
			return;
		}		
		var canSend = opts.onSend();
		if (!canSend) {
			return;
		}	
		
		var tmpName = 'upload_frame_' + (frameCount++);		
		var iframe = $("<iframe style='position:absolute;top:-9999px;display:none;' name='"+tmpName+"' id='"+tmpName+"'></iframe>");
		iframe.load(function() {
			var contents = $(this).contents().get(0);
			var data = $(contents).find('body').html();
			if(!data) return;
			if ('json' == opts.dataType) {
				data = eval('(' + data + ')');
			}
			opts.onComplate(data);
			setTimeout(function() {
				iframe.remove();				
			}, 2000);
		});
		iframe.appendTo("body");
		
		var form = $('#'+opts.formId);
		form.attr("target", tmpName).attr('action', opts.url);			
		form.submit();
	};
})(jQuery);